import React, { useState, useRef, useEffect } from 'react';
import MDEditor from '@uiw/react-md-editor';
import { commands } from '@uiw/react-md-editor';
import { PictureOutlined, InboxOutlined } from '@ant-design/icons';
import { Input, Upload, Button, message, Tabs, Space, Popover, InputNumber, Image } from 'antd';
import { UploadOutlined, LinkOutlined } from '@ant-design/icons';
import type { UploadFile, UploadProps } from 'antd';
import rehypeHighlight from 'rehype-highlight';
import rehypeKatex from 'rehype-katex';
import remarkMath from 'remark-math';
import "highlight.js/styles/atom-one-light.css";
import 'katex/dist/katex.min.css';  

const { Dragger } = Upload;

interface CustomMDEditorProps {
  value?: string;
  onChange?: (value?: string) => void;
  height?: number;
  preview?: 'edit' | 'preview' | 'live';
  placeholder?: string;
  'data-color-mode'?: 'light' | 'dark';
}

const CustomMDEditor: React.FC<CustomMDEditorProps> = ({
  value,
  onChange,
  height = 300,
  preview = 'edit',
  placeholder,
  'data-color-mode': colorMode = 'light'
}) => {
  const [showImagePopover, setShowImagePopover] = useState(false);
  const [activeTab, setActiveTab] = useState('url');
  const [imageUrl, setImageUrl] = useState('');
  const [uploading, setUploading] = useState(false);
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [editor, setEditor] = useState<any>(null);
  const editorRef = useRef<HTMLDivElement>(null);
  const [isFocused, setIsFocused] = useState(false);
  const [previewImageUrl, setPreviewImageUrl] = useState('');
  const [imageWidth, setImageWidth] = useState<number>(300);
  const [imageHeight, setImageHeight] = useState<number>();

  const handleUrlConfirm = () => {
    if (!imageUrl.trim()) {
      message.error('请输入图片URL');
      return;
    }
    
    // 简单的URL格式验证
    const urlPattern = /^(https?:\/\/)([\da-z\.-]+)\.([a-z\.]{2,6})([\/ \w \.-]*)*\/?$/;
    if (!urlPattern.test(imageUrl)) {
      message.error('请输入有效的图片URL');
      return;
    }
    
    insertImage(imageUrl);
    handleClose();
  };

  const insertImage = (url: string, width?: number, height?: number) => {
    const sizeStyle = [];
    if (width) sizeStyle.push(`width="${width}px"`);
    if (height) sizeStyle.push(`height="${height}px"`);
    const sizeAttr = sizeStyle.length > 0 ? ` ${sizeStyle.join(' ')}` : '';
    
    const imageHtml = `<img src="${url}" alt="图片"${sizeAttr} />`;
    
    if (editor && editor.api) {
      const { api } = editor;
      api.replaceSelection(imageHtml);
    } else {
      // 如果没有editor实例，直接通过onChange插入
      const newValue = value ? value + '\n' + imageHtml : imageHtml;
      onChange?.(newValue);
    }
  };

  const handleClose = () => {
    setImageUrl('');
    setFileList([]);
    setActiveTab('url');
    setShowImagePopover(false);
    setPreviewImageUrl('');
    setImageWidth(300);
    setImageHeight(undefined);
  };

  const handleInsertWithSize = () => {
    if (activeTab === 'upload' && previewImageUrl) {
      insertImage(previewImageUrl, imageWidth, imageHeight);
      handleClose();
    } else if (activeTab === 'url' && imageUrl.trim()) {
      insertImage(imageUrl, imageWidth, imageHeight);
      handleClose();
    } else {
      message.error('请先上传图片或输入图片URL');
    }
  };

  // 处理剪贴板图片粘贴
  const handlePaste = async (event: ClipboardEvent) => {
    // 只有当前编辑器获得焦点时才处理粘贴事件
    if (!isFocused) return;
    
    const items = event.clipboardData?.items;
    if (!items) return;

    for (let i = 0; i < items.length; i++) {
      const item = items[i];
      if (item.type.indexOf('image') !== -1) {
        event.preventDefault();
        const file = item.getAsFile();
        if (file) {
          await uploadClipboardImage(file);
        }
        break;
      }
    }
  };

  // 上传图片函数
  const uploadImage = async (file: File): Promise<string> => {
    const formData = new FormData();
    formData.append('file', file);

    try {
      const response = await fetch('http://118.24.164.222:8080/api/file/upload', {
        method: 'POST',
        headers: {
          'authorization': 'eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX3JvbGUiOiJURUFDSEVSIiwidXNlcl9pZCI6MSwiZXhwIjoxNzU0MDM3MDY3fQ.TakDRwBii18cFOUZuNqbHeuuOXO870-TLnUx4kkHxwQ'
        },
        body: formData
      });

      if (!response.ok) {
        message.error('上传失败，服务器错误');
        throw new Error('上传失败');
      }

      const result = await response.json();
      console.log('图片上传响应:', result);
      
      // 检查返回的code字段
      if (result.code === 0) {
        message.error(result.message || '上传失败');
        throw new Error(result.message || '上传失败');
      }
      
      if (result.code === 200 && result.data) {
        message.success('图片上传成功');
        // 直接返回data字段中的URL，去除可能的空格
        return result.data.trim();
      }
      
      message.error('上传失败，返回数据格式错误');
      throw new Error('返回数据格式错误');
    } catch (error) {
      console.error('图片上传失败:', error);
      if (error instanceof Error && !error.message.includes('上传失败')) {
        message.error('网络错误，请检查网络连接');
      }
      throw error;
    }
  };

  // 上传剪贴板图片
  const uploadClipboardImage = async (file: File) => {
    try {
      setUploading(true);
      const imageUrl = await uploadImage(file);
      insertImage(imageUrl); // 直接插入，不设置大小
    } catch (error) {
      console.error('剪贴板图片上传失败:', error);
    } finally {
      setUploading(false);
    }
  };

  // 添加粘贴事件监听和焦点管理
  useEffect(() => {
    const handlePasteEvent = (e: ClipboardEvent) => handlePaste(e);
    document.addEventListener('paste', handlePasteEvent);
    
    const editorElement = editorRef.current;
    if (editorElement) {
      const handleFocus = () => setIsFocused(true);
      const handleBlur = () => setIsFocused(false);
      
      editorElement.addEventListener('focusin', handleFocus);
      editorElement.addEventListener('focusout', handleBlur);
      
      return () => {
        document.removeEventListener('paste', handlePasteEvent);
        editorElement.removeEventListener('focusin', handleFocus);
        editorElement.removeEventListener('focusout', handleBlur);
      };
    }
    
    return () => {
      document.removeEventListener('paste', handlePasteEvent);
    };
  }, [isFocused, value, onChange]);

  const uploadProps: UploadProps = {
    name: 'file',
    action: 'http://1.95.134.113:8080/upload',
    headers: {
      'token': 'eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoi5bCP6bif5ri45pif6YeOIiwiaWQiOjIsInVzZXJuYW1lIjoiYWRtaW4iLCJleHAiOjE3NTQwMjE5OTR9.seEd8FLNSB0jgT0GOA3mt90uaLsWoXeF9eb38qDIj_w'
    },
    fileList,
    beforeUpload: (file) => {
      const isImage = file.type?.startsWith('image/');
      if (!isImage) {
        message.error('只能上传图片文件!');
        return false;
      }
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        message.error('图片大小不能超过5MB!');
        return false;
      }
      return true;
    },
    customRequest: async ({ file, onSuccess, onError }) => {
      try {
        setUploading(true);
        const imageUrl = await uploadImage(file as File);
        onSuccess?.(imageUrl);
        setPreviewImageUrl(imageUrl);
      } catch (error) {
        onError?.(error as Error);
      } finally {
        setUploading(false);
      }
    },
    maxCount: 1,
    accept: 'image/*'
  };

  const tabItems = [
    {
      key: 'url',
      label: (
        <span>
          <LinkOutlined />
          URL链接
        </span>
      ),
      children: (
        <div style={{ width: 400 }}>
          <Input
            placeholder="请输入图片URL地址"
            value={imageUrl}
            onChange={(e) => {
               setImageUrl(e.target.value);
             }}
            onPressEnter={handleUrlConfirm}
            style={{ marginBottom: 12 }}
            onFocus={(e) => e.stopPropagation()}
            onClick={(e) => e.stopPropagation()}
          />
          
          {/* URL图片预览区域 */}
          {imageUrl.trim() && (
            <div style={{ marginBottom: 12, textAlign: 'center' }}>
              <Image
                src={imageUrl}
                alt="预览"
                style={{ maxWidth: '100%', maxHeight: 200 }}
                preview={false}
              />
            </div>
          )}
          
          {/* 大小设置 */}
          <div style={{ marginBottom: 12 }}>
            <Space>
              <span>宽度:</span>
              <InputNumber
                size="small"
                value={imageWidth}
                onChange={(value) => setImageWidth(value || 300)}
                min={50}
                max={1000}
                placeholder="宽度"
                addonAfter="px"
              />
              <span>高度:</span>
              <InputNumber
                size="small"
                value={imageHeight}
                onChange={(value) => setImageHeight(value || undefined)}
                min={50}
                max={1000}
                placeholder="自动"
                addonAfter="px"
              />
            </Space>
          </div>
          
          <div style={{ textAlign: 'right' }}>
            <Space>
              <Button size="small" onClick={handleClose}>取消</Button>
              <Button size="small" type="primary" onClick={handleInsertWithSize}>
                插入图片
              </Button>
            </Space>
          </div>
        </div>
      )
    },
    {
      key: 'upload',
      label: (
        <span>
          <UploadOutlined />
          上传图片
        </span>
      ),
      children: (
         <div style={{ width: 400 }}>
           {/* 拖拽上传区域 */}
            <Dragger
              {...uploadProps}
              style={{ marginBottom: 12, minHeight: previewImageUrl ? 'auto' : 120 }}
              showUploadList={false}
            >
              {previewImageUrl ? (
                <div style={{ padding: '12px', textAlign: 'center' }}>
                  <Image
                    src={previewImageUrl}
                    alt="预览"
                    style={{ maxWidth: '100%', maxHeight: 200, borderRadius: 4 }}
                    preview={false}
                  />
                  <p style={{ margin: '8px 0 0 0', fontSize: 12, color: '#666' }}>
                    上传成功，可重新拖拽或点击更换图片
                  </p>
                </div>
              ) : (
                <>
                  <p className="ant-upload-drag-icon">
                    <InboxOutlined style={{ fontSize: 48, color: '#1890ff' }} />
                  </p>
                  <p className="ant-upload-text">
                    {uploading ? '上传中...' : '点击或拖拽图片到此区域上传'}
                  </p>
                  <p className="ant-upload-hint">
                    支持图片格式，文件大小不超过5MB
                  </p>
                </>
              )}
            </Dragger>
           
           {/* 大小设置 */}
           {previewImageUrl && (
             <div style={{ marginBottom: 12 }}>
               <Space>
                 <span>宽度:</span>
                 <InputNumber
                   size="small"
                   value={imageWidth}
                   onChange={(value) => setImageWidth(value || 300)}
                   min={50}
                   max={1000}
                   placeholder="宽度"
                   addonAfter="px"
                 />
                 <span>高度:</span>
                 <InputNumber
                   size="small"
                   value={imageHeight}
                   onChange={(value) => setImageHeight(value || undefined)}
                   min={50}
                   max={1000}
                   placeholder="自动"
                   addonAfter="px"
                 />
               </Space>
             </div>
           )}
           
           <div style={{ fontSize: 12, color: '#999', marginBottom: 12, textAlign: 'center' }}>
             也可以直接粘贴剪贴板中的图片
           </div>
           
           <div style={{ textAlign: 'right' }}>
             <Space>
               <Button size="small" onClick={handleClose} disabled={uploading}>
                 取消
               </Button>
               {previewImageUrl && (
                 <Button size="small" type="primary" onClick={handleInsertWithSize} disabled={uploading}>
                   插入图片
                 </Button>
               )}
             </Space>
           </div>
         </div>
       )
    }
  ];

  const imagePopoverContent = (
    <div onClick={(e) => e.stopPropagation()} style={{ padding: '12px' }}>
      <Tabs
        activeKey={activeTab}
        onChange={setActiveTab}
        items={tabItems}
        size="small"
      />
    </div>
  );

  // 自定义图片插入命令
  const customImageCommand = {
    name: 'image',
    keyCommand: 'image',
    buttonProps: { 'aria-label': '插入图片', title: '插入图片' },
    icon: (
      <Popover
        content={imagePopoverContent}
        title="插入图片"
        trigger="click"
        open={showImagePopover}
        onOpenChange={(open) => {
          setShowImagePopover(open);
          if (!open) {
            handleClose();
          }
        }}
        getPopupContainer={(triggerNode) => {
          // 在全屏模式下，确保弹窗渲染在正确的容器中
          const fullscreenContainer = document.querySelector('.w-md-editor-fullscreen');
          return (fullscreenContainer || document.body) as HTMLElement;
        }}
        placement="bottomLeft"
      >
        <PictureOutlined style={{ fontSize: 14 }} />
      </Popover>
    ),
    execute: (state: any, api: any) => {
       // 保存当前编辑器实例和API
       setEditor({ state, api });
       // 切换气泡显示状态
       setShowImagePopover(!showImagePopover);
     }
  };

  // 保留完整的工具栏命令，包括预览控制
  const customCommands = [
    commands.bold,
    commands.italic,
    commands.strikethrough,
    commands.hr,
    commands.group([
      commands.title1,
      commands.title2,
      commands.title3,
      commands.title4,
      commands.title5,
      commands.title6,
    ], {
      name: 'title',
      groupName: 'title',
      buttonProps: { 'aria-label': '插入标题', title: '插入标题' }
    }),
    commands.divider,
    commands.link,
    customImageCommand, // 使用自定义图片命令
    commands.code,
    commands.codeBlock,
    commands.divider,
    commands.quote,
    commands.unorderedListCommand,
    commands.orderedListCommand,
    commands.checkedListCommand,
    commands.divider,
    commands.table,
    commands.divider,
    commands.help
  ];

  // 保留右侧的预览控制工具
  const extraCommands = [
    commands.codeEdit,
    commands.codeLive,
    commands.codePreview,
    commands.divider,
    commands.fullscreen
  ];

  return (
    <div ref={editorRef} className="customEditor" data-color-mode={colorMode}>
      <MDEditor
        value={value}
        onChange={onChange}
        height={height}
        preview={preview}
        data-color-mode={colorMode}
        commands={customCommands}
        extraCommands={extraCommands}
        textareaProps={{
          placeholder: placeholder || '请输入内容...',
          style: {
            fontSize: 14,
            lineHeight: 1.6,
            fontFamily: 'Monaco, Menlo, "Ubuntu Mono", monospace'
          }
        }}
        previewOptions={{
          remarkPlugins: [remarkMath],
          rehypePlugins: [[rehypeHighlight, { detect: true }], rehypeKatex]
        }}
      />
    </div>
  );
};

export default CustomMDEditor;